package com.sun.dailyprj.androidx.viewmodel;

import android.os.Bundle;
import android.view.View;

import androidx.activity.ComponentActivity;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.sun.dailyprj.R;
import com.sun.dailyprj.androidx.viewmodel.bean.Person;
import com.sun.dailyprj.androidx.viewmodel.model.NameViewModel;
import com.sun.dailyprj.databinding.ActivityLivedataStudyBinding;
import com.sun.dailyprj.util.Logger;

/*
 * =====================================================================================
 * Summary:
 *
 * File: ViewModelTestActivity.java
 * Author: Yanpeng.Sun
 * Create: 2019/11/25 10:07
 * =====================================================================================
 */
public class ViewModelTestActivity extends AppCompatActivity{
    private ActivityLivedataStudyBinding mBinding;
    private NameViewModel mViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_livedata_study);
        mBinding.setVmta(this);
        mViewModel = ViewModelProviders.of(this).get(NameViewModel.class);
        mViewModel.getCurrentName().observe(this, new Observer<Person>(){
            @Override
            public void onChanged(Person person) {
                mBinding.txtStudyInfo.setText("name:" + person.getName()
                        + "\n sex:" + person.getSex()
                        + "\n age:" + person.getAge());
                Logger.debug("onChanged():" + person.toString());
            }
        });
    }


    public void onUpdateData(View v) {
        Logger.debug("onUpdateData() click");
        new Thread(new Runnable(){
            @Override
            public void run() {
                Person person = new Person();
                person.setName("张三");
                person.setSex("男");
                for(int i=0;i<100;i++) {
                    person.setAge(i);
                    mViewModel.getCurrentName().postValue(person);
                    try{
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public void onRoomData(View view) {

    }
}
